# include "serialib.h"
# include "serial_player.h"

int main(int argc, char* argv[]) 
{
    std::string virtualTx1 = "/tmp/virtual1_tx";
    std::string virtualRx1 = "/tmp/virtual1_rx";
    unsigned int baudRate1 = 115200;
    std::string logFile1;

    std::string virtualTx2 = "/tmp/virtual2_tx";
    std::string virtualRx2 = "/tmp/virtual2_rx";
    unsigned int baudRate2 = 115200;
    std::string logFile2;
    
    if (argc < 7) {
        std::cerr << "用法: " << argv[0] << " <日志文件1> [波特率] [端口名称] <日志文件2> [波特率] [端口名称]" << std::endl;
        return 1;
    }

    logFile1 = argv[1];
    try 
    { 
        baudRate1 = std::stoi(argv[2]); 
    } 
    catch (...) 
    { 
        std::cerr << "无效的波特率，使用默认值: " << baudRate1 << std::endl; 
    }
    std::string virtualPort = argv[3];
    virtualTx1 = virtualPort + "_tx";
    virtualRx1 = virtualPort;

    logFile2 = argv[4];
    try 
    { 
        baudRate2 = std::stoi(argv[5]); 
    } 
    catch (...) 
    { 
        std::cerr << "无效的波特率，使用默认值: " << baudRate2 << std::endl; 
    }
    virtualPort = argv[6];
    virtualTx2 = virtualPort + "_tx";
    virtualRx2 = virtualPort;

    serial_player m_player1(virtualTx1, virtualRx1, baudRate1, logFile1);
    serial_player m_player2(virtualTx2, virtualRx2, baudRate2, logFile2);

    auto startTime = std::chrono::high_resolution_clock::now();
    double prevTimestamp = std::min(m_player1.getFirstTimestamp(), m_player2.getFirstTimestamp());

    if (getCurrentTimeAsDouble() < prevTimestamp)
    {
        throw std::logic_error("时间错误：记录的时间戳晚于当前时间");
    }
    
    std::thread p1([&]() -> void{
        m_player1.play(startTime, prevTimestamp);
    });

    std::thread p2([&]() -> void{
        m_player2.play(startTime, prevTimestamp);
    });

    p1.join();
    p2.join();
}